const jsonwebtoken = require("jsonwebtoken");
const config = require("../../config/config.json");
const {
  createToken,
  createToken_refresh,
} = require("../../jsonwebtoken/index");

function RefreshToken(req, res) {
  const refreshToken = req.body.refreshToken.replace("Bearer ", "");
  if (!refreshToken) {
    res.send({
      status: 401,
      message: "NO TOKEN PROVIDED",
    });
  }

  jsonwebtoken.verify(refreshToken, config.jwt.secret, (err, decoded) => {
    if (err) {
      res.send({
        status: 500,
        message: "Failed to Authenticate Token",
      });
    } else {
      res.send({
        status: 0,
        data: {
          message: "success",
          accessToken: createToken({
            username: decoded.username,
          }),
          refreshToken: createToken_refresh({
            username: decoded.username,
          }),
        },
      });
    }
  });
}

module.exports = { RefreshToken };
